package xyz.naokeziteng.data_structure.balancetree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hawk
 * @date 2022/9/21
 * @desc AVL树
 **/
public class AVLTree<K extends Comparable<K>, V> {

    private class Node {
        private K key;
        private V value;
        private Node left, right;
        //树的高度
        private int height;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
            left = null;
            right = null;
            height = 1;
        }
    }

    private Node root;
    private int size;

    public AVLTree() {
        root = null;
        size = 0;
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    //判断是否是二分搜索树
    public boolean isBST() {
        List<K> keys = new ArrayList<>();
        inOrder(root, keys);
        for (int i = 1; i < keys.size(); i++) {
            if (keys.get(i - 1).compareTo(keys.get(i)) > 0) {
                return false;
            }
        }
        return true;
    }

    //判断二叉树是否是一颗平衡二叉树
    public boolean isBalanced() {
        return isBalanced(root);
    }

    private boolean isBalanced(Node node) {
        if (node == null) {
            return true;
        }
        if (Math.abs(getBalanceFactor(node)) > 1) {
            return false;
        }
        return isBalanced(node.left) && isBalanced(node.right);
    }

    //中序遍历
    private void inOrder(Node node, List<K> keys) {
        if (node == null) {
            return;
        }
        inOrder(node.left, keys);
        keys.add(node.key);
        inOrder(node.right, keys);

    }

    //获取节点高度
    private int getHeight(Node node) {
        return node == null ? 0 : node.height;
    }

    //获得节点平衡因子
    private int getBalanceFactor(Node node) {
        if (node == null) {
            return 0;
        }
        return getHeight(node.left) - getHeight(node.right);
    }

    //向二分搜索树中添加新的元素
    public void add(K key, V value) {
        root = add(root, key, value);
    }

    //向以Node为根的二分搜索树中添加元素(key, value),递归算法
    //返回插入新节点后的根
    private Node add(Node node, K key, V value) {
        if (node == null) {
            size++;
            return new Node(key, value);
        }

        if (key.compareTo(node.key) < 0) {
            node.left = add(node.left, key, value);
        } else if (key.compareTo(node.key) > 0) {
            node.right = add(node.right, key, value);
        } else {
            node.value = value;
        }

        //更新height
        node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;

        //计算平衡因子
        int balanceFactor = getBalanceFactor(node);

        //平衡维护
        //LL
        if (balanceFactor > 1 && getBalanceFactor(node.left) >= 0) {
            return rightRotate(node);
        }
        //RR
        if (balanceFactor < -1 && getBalanceFactor(node.right) <= 0) {
            return leftRotate(node);
        }
        //LR
        if (balanceFactor > 1 && getBalanceFactor(node.left) < 0) {
            node.left = leftRotate(node.left);
            return rightRotate(node);
        }
        //RL
        if (balanceFactor < -1 && getBalanceFactor(node.right) > 0) {
            node.right = rightRotate(node.right);
            return leftRotate(node);
        }

        return node;
    }

    //删除任意节点
    public void remove(K key) {
        root = remove(root, key);
    }

    //删除任意节点，分三种情况
    //被删除节点左子树为空，右子树直接替换
    //被删除节点右子树为空，左子树直接替换
    //被删除节点左右子树都不为空,有两种做法，找到右子树中的最小值或者左子树中的最大值，来替换被删除节点
    private Node remove(Node node, K key) {
        if (node == null) {
            return null;
        }
        Node retNode;
        if (node.key.compareTo(key) < 0) {
            node.right = remove(node.right, key);
            retNode = node;
        } else if (node.key.compareTo(key) > 0) {
            node.left = remove(node.left, key);
            retNode = node;
        } else {
            if (node.left == null) {
                Node rightNode = node.right;
                node.right = null;
                size--;
                retNode = rightNode;
            } else if (node.right == null) {
                Node leftNode = node.left;
                node.left = null;
                size--;
                retNode = leftNode;
            } else {
                //找到右子树最小值
                Node successor = minmum(node.right);
                //删除右子树最小值
                successor.right = remove(node.right,successor.key);
                successor.left = node.left;

                node.left = node.right = null;
                retNode = successor;
            }
        }

        if(retNode == null) {
            return null;
        }

        //更新height
        retNode.height = Math.max(getHeight(retNode.left), getHeight(retNode.right)) + 1;

        //计算平衡因子
        int balanceFactor = getBalanceFactor(retNode);

        //平衡维护
        //LL
        if (balanceFactor > 1 && getBalanceFactor(retNode.left) >= 0) {
            return rightRotate(retNode);
        }
        //RR
        if (balanceFactor < -1 && getBalanceFactor(retNode.right) <= 0) {
            return leftRotate(retNode);
        }
        //LR
        if (balanceFactor > 1 && getBalanceFactor(retNode.left) < 0) {
            retNode.left = leftRotate(retNode.left);
            return rightRotate(retNode);
        }
        //RL
        if (balanceFactor < -1 && getBalanceFactor(retNode.right) > 0) {
            retNode.right = rightRotate(retNode.right);
            return leftRotate(retNode);
        }
        return retNode;
    }

    // 寻找二分搜索树的最小元素
    public V minmum() {
        if (size == 0) {
            throw new IllegalArgumentException("BST is empty!");
        }
        return minmum(root).value;
    }

    //返回以node为根的二分搜索树的最小值所在的节点
    private Node minmum(Node node) {
        if (node.left == null) {
            return node;
        }

        return minmum(node.left);
    }
    // 寻找二分搜索树的最大元素
    public V maxmum() {
        if (size == 0) {
            throw new IllegalArgumentException("BST is empty!");
        }
        return maxmum(root).value;
    }

    //返回以node为根的二分搜索树的最大值所在的节点
    private Node maxmum(Node node) {
        if (node.right == null) {
            return node;
        }

        return minmum(node.right);
    }


    //对节点y进行向右旋转操作，返回旋转后新的根节点x
    //       y                             x
    //      / \                          /   \
    //     x  T4     向右旋转（y）        z     y
    //    / \      - - - - - - - ->   / \   / \
    //   z  T3                       T1 T2 T3 T4
    //  / \
    // T1  T2
    private Node rightRotate(Node y) {
        Node x = y.left;
        Node t3 = x.right;
        y.left = t3;
        x.right = y;
        //更新height
        y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
        x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;
        return x;
    }


    //对节点y进行向左旋转操作，返回旋转后新的根节点x
    //       y                             x
    //      / \                          /   \
    //     T1  x     向右旋转（y）        y     z
    //        / \   - - - - - - - ->   / \   / \
    //      T2   z                    T1 T2 T3 T4
    //          / \
    //         T3  T4
    private Node leftRotate(Node y) {
        Node x = y.right;
        Node t2 = x.left;
        //向左旋转
        y.right = t2;
        x.left = y;
        //更新height
        y.height = Math.max(getHeight(y.left), getHeight(y.right)) + 1;
        x.height = Math.max(getHeight(x.left), getHeight(x.right)) + 1;
        return x;
    }
}
